<template>
  <div>
    <el-upload
      ref="upload"
      :action="`${SERVER.DMSCLOUD_BASEDATA}/commonDatas/${actionType}/upload`"
      :accept="accept"
      :file-list="fileList"
      :list-type="listType"
      :multiple="multiple"
      :before-upload="beforeUpload"
      :on-remove="onRemove"
      :on-change="onChange"
      :on-success="onSuccess"
      class="upload-demo"
      drag>
      <i class="el-icon-upload"/>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div slot="tip" class="el-upload__tip">{{ tips }}</div>
    </el-upload>
  </div>
</template>

<script>
import SERVER from '@/api/server'
export default {
  name: 'Upload',
  props: {
    'url': String,
    'tip': String,
    'accept': String,
    'original': Object,
    'size': Number,
    'disabled': Boolean,
    'tips': String,
    'multiple': Boolean,
    actionType: {
      type: String,
      default: () => 'file'
    }
  },
  data() {
    return {
      fileList: [],
      SERVER: SERVER
    }
  },
  computed: {
    listType() {
      if (this.accept && (this.accept.indexOf('png') > 0 || this.accept.indexOf('jpg') > 0)) {
        return 'picture'
      }
      return 'text'
    }
  },
  watch: {
    original(val) {
      const index = this.fileList.findIndex(file => {
        if (file['response']) {
          const data = file['response']['data'] || file['response']
          return data['url'] === val
        }
        return false
      })
      if (index < 0) {
        this.init(val)
      }
    }
  },
  mounted() {
    this.init(this.original)
  },
  methods: {
    init(val) {
      if (val) {
        this.fileList = [{ name: val.substring(val.lastIndexOf('/') + 1), url: val }]
      } else {
        this.fileList = []
      }
    },
    beforeUpload(file) {
      if (this.size && file.size > this.size) {
        this.$message.error(this.tip)
        this.fileList = []
        return false
      }

      if (!this.accept) {
        return true
      }
      const arr = this.accept.split(',')
      const suffix = file.name.substring(file.name.lastIndexOf('.'))
      const isRight = arr.findIndex(val => val.toUpperCase() === suffix.toUpperCase()) >= 0

      if (!isRight && this.tip) {
        this.$message.error(this.tip)
      }
      return isRight
    },
    onChange(file, fileList) {
      if (fileList.length > 1) {
        this.fileList = fileList.slice(-1)
      }
    },
    onRemove() {
      this.fileList = []
      this.$emit('uploaded', {})
    },
    onSuccess(response, file, fileList) {
      debugger
      if (response) {
        this.fileList.push({ name: response.name, url: response.file_id })
        this.$emit('uploaded', response)
      } else {
        this.fileList = []
      }
    }
  }
}
</script>

<style scoped>
</style>
